<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\DistributionShopRedPacketModel;

class DistributionShopRedPacketController extends BackgroundController {
	
	protected function _initialize() {
		$this->setControllerTitle('红包管理');
		$this->setActionTitle(array(
			'index' => '红包列表',
	        'add' => '添加红包',
		));
		$this->setActionNav(array(
			'index',
			'add'
		));
	}
	
	/**
	 * 红包列表
	 */
	public function getLists() {
		$page = $this->getPage ();
		$pagesize = $this->getPageSize ();
		$d = M("DistributionShopRedPacket");
		$condition = array (
			'cid' => $this->aid,
		);
		$redPacketLists = $d->where ( $condition )->limit ( $pagesize )->page ( $page )->order ( 'id DESC' )->select ();
		$redPacketCount = $d->where ( $condition )->count ();
		foreach ( $redPacketLists as &$v ) {
			$v['efficacyStautus'] = DistributionShopRedPacketModel::$EFFICACYS[$v['efficacy']];
		}
		$this->assign ( 'redPacketLists', $redPacketLists );
		$this->showPage ( $redPacketCount, $pagesize );
		$this->display();
	}
	
	/**
	 * 添加红包
	 * @see \Utuo\BackgroundController::addAction()
	 */
	public function addAction() {
		$this->display();
	}
	
	/**
	 * 提交增加红包
	 */
	public function addPostAction() {
		$value = I('value', 10, "intval");
		$fulfil = I('fulfil', 100, "intval");
		$count = I('count', 10, "intval");
		$createTime = time();
		$endTime = I('endTime', 0, "strtotime");
		$tag = I('tag', "");
		
		$data = array();
		for( $i = 0; $i < $count; $i++ ) {
			$c = preg_replace('/(0\.)|\s/', '', microtime());
			$data[] = array(
				'code' => $c,
				'cid' => $this->aid,
				'value' => $value,
				'fulfil' => $fulfil,
				'efficacy' => 0,
				'createTime' => $createTime,
				'endTime' => $endTime,
				'tag' => $tag,
			);
		}
		false !== M("DistributionShopRedPacket")->addAll($data) and $this->ajaxSuccess("添加成功");
		$this->ajaxError("添加失败");
	}
	
}